package rpc.core.plugin.impl;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import rpc.bootstrap.springboot.Bootstrap;
import rpc.core.FlowMap;
import rpc.core.plugin.ServicePlugin;
import rpc.core.plugin.impl.proxy.ServiceProxy;
import rpc.utils.ReflectionUtils;

/*********
 *
 *
 *@author 197
 *@date 2020/8/6 16:49
 *
 **/


public class RpcServerServicePlugin implements ServicePlugin {


  private static final Logger logger = LoggerFactory.getLogger(FlowServicePlugin.class);

  private final int queueSize = 1000;
  private final ApplicationContext context;
  private final Environment environment;
  private final Map<String, ServiceProxy> flowProxyMap = new HashMap<>();
  private final Bootstrap bootstrap;
  private final ServicePlugin servicePlugin;

  public RpcServerServicePlugin(ApplicationContext context, Environment environment, Bootstrap bootstrap, ServicePlugin servicePlugin) {
    this.context = context;
    this.environment = environment;
    this.bootstrap = bootstrap;
    this.servicePlugin = servicePlugin;
  }

  @Override
  public void init() {
    Map<String, ServiceProxy> flowServiceProxy = servicePlugin.getFlowServiceProxy();
    bootstrap.getServiceBeanList().forEach(c -> {
      int serviceId = ReflectionUtils.getFliedIntValue(c.getInterfaceClass(), "serviceId");
      String simpleName = c.getInterfaceClass().getSimpleName().toLowerCase();
      Arrays.stream(c.getInterfaceClass().getDeclaredMethods()).forEach(m -> {
        String flowName = simpleName + "." + m.getName().toLowerCase();
        flowProxyMap.put(flowName, flowServiceProxy.get(flowName));
        flowProxyMap.put(serviceId + "." + ReflectionUtils.getFliedIntValue(c.getInterfaceClass(), m.getName() + "_MsgId"), flowServiceProxy.get(flowName));
      });
    });
    if (logger.isDebugEnabled()) {
      logger.debug("flowProxySet:{}", String.join(",", flowProxyMap.keySet()));
    }
  }

  @Override
  public Set<String> getFlowName() {
    return flowProxyMap.keySet();
  }

  @Override
  public void close() {
  }

  @Override
  public Map<String, ServiceProxy> getFlowServiceProxy() {
    return flowProxyMap;
  }

  @Override
  public Map<String, Object> dump() {
    FlowMap flowMap = new FlowMap();
//    flowMap.append("activeCount", executor);
    return flowMap.toMap();
  }
}
